﻿using System;
using System.Linq;

namespace FBGraph.ClientGenerator.CodeGen
{
    public class Method : Member
    {
        public Method(String name, TypeReference type, params Parameter[] parameters)
        {
            this.Name = name;
            this.Accessibility = "public";

            this.TypeArguments = new TypeArgumentsList();
            this.Parameters = new ParameterList(parameters);
        }

        public String Accessibility { get; set; }
        public TypeReference BaseType { get; set; }
        public String Name { get; set; }
        public ParameterList Parameters { get; private set; }
        public TypeArgumentsList TypeArguments { get; private set; }
        public TypeReference ExplicitImplementationType { get; set; }
        public String Body { get; set; }
        public BodyWriter GetBodyWriter()
        {
            return new BodyWriter(body => this.Body = body);
        }

        protected override void WriteBody(CodeGenWriter writer)
        {
            foreach(var bodyLine in this.Body.Split(new String[] { Environment.NewLine }, StringSplitOptions.None))
                writer.WriteLine(bodyLine);
        }

        protected override void WriteDeclaration(CodeGenWriter writer)
        {
            if (this.ExplicitImplementationType == null)
            {
                writer.Write(this.Accessibility);
                writer.Write(' ');
            }

            if (this.BaseType == null) writer.Write("void");
            else writer.Write(this.BaseType);
            writer.Write(' ');

            if (this.ExplicitImplementationType != null)
            {
                writer.Write(this.ExplicitImplementationType);
                writer.Write('.');
            }

            writer.Write(this.Name);

            writer.Write(this.TypeArguments);
            writer.Write('(');
            writer.Write(this.Parameters);
            writer.WriteLine(')');
        }
    }
}